<template>
    <div class="app-container">

        <div class="filter-container" style="display: flex; align-items: flex-start;">

            <el-date-picker
                    v-model="listQuery.searchStatTimeStart"
                    type="date"
                    placeholder="开始日期"
                    format="yyyy-MM-dd"
                    :picker-options="pickerStartOption">
            </el-date-picker>

            <el-date-picker
                    v-model="listQuery.searchStatTimeEnd"
                    type="date"
                    placeholder="结束日期"
                    :picker-options="pickerEndOption">
            </el-date-picker>

            <el-select clearable style="width: 150px" class="filter-item" v-model="listQuery.searchChannel" placeholder="推广渠道" @change="handleFilter">
                <el-option v-for="item in channelOptions" :key="item" :label="item.name" :value="item.key">
                </el-option>
            </el-select>

            <i style="padding-left: 50px;line-height: 36px;">课程名称: </i>
            <el-input style="width: 200px;" class="filter-item" v-model="courseName" disabled="disabled"></el-input>

            <el-button class="filter-item" style="margin-left: 20px;" type="primary" icon="search" @click="handleFilter">搜索</el-button>
            <el-button class='filter-item' style="margin-left: 20px;" type="primary" icon="document" @click="handleDownload">导出excel</el-button>
        </div>

        <el-table :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row>

            <el-table-column label='日期' align="center">
                <template scope="scope">
                    {{scope.row.statDate|parseDate('day')}}
                </template>
            </el-table-column>
            <el-table-column label="百度PV" align="center">
                <template scope="scope">
                    {{scope.row.pvCount ? scope.row.pvCount : '0'}}
                </template>
            </el-table-column>
            <el-table-column label="百度UV" align="center">
                <template scope="scope">
                    {{scope.row.uvCount ? scope.row.uvCount : '0'}}
                </template>
            </el-table-column>
            <el-table-column label="登陆用户的访问次数" align="center">
                <template scope="scope">
                    {{scope.row.accessCount ? scope.row.accessCount : '0'}}
                </template>
            </el-table-column>
            <el-table-column label="下单数" align="center">
                <template scope="scope">
                    {{scope.row.totalCount ? scope.row.totalCount : '0'}}
                </template>
            </el-table-column>
            <el-table-column label="下单金额" align="center">
                <template scope="scope">
                    ￥{{scope.row.totalAmount|priceFormat}}元
                </template>
            </el-table-column>
            <el-table-column label="成交订单数" align="center">
                <template scope="scope">
                    {{scope.row.dealCount ? scope.row.dealCount : '0'}}
                </template>
            </el-table-column>
            <el-table-column label="成交金额" align="center">
                <template scope="scope">
                    ￥{{scope.row.dealAmount|priceFormat}}元
                </template>
            </el-table-column>
        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
                           :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import { getCourseDetailList } from '@/api/statcourse';
    import { getDetail as getCourseDetail } from '@/api/course';
    import { priceFormat, parseTime, parseDate } from '@/filters/index';

    export default {
        data() {
            return {
                list: null,
                total: null,
                courseName: '',
                listQuery: {
                    page: 1,
                    pageSize: 30,
                    searchCourseId: '',
                    searchChannel: '',
                    searchStatTimeStart: new Date((new Date()).getTime() - 30 * 24 * 3600 * 1000),
                    searchStatTimeEnd: new Date()
                },
                channelOptions: [
                    { name: '选择渠道', key: '' },
                    { name: '泰迪熊', key: 'TED' },
                    { name: '微信', key: 'WX' }
                ],
                listLoading: true,
                pickerStartOption: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                pickerEndOption: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                }
            }
        },
        created() {
            const reg = /\/(\d*)$/
            if (reg.test(this.$route.path)) {
                this.isUpdate = true;
                const ID = RegExp.$1;
                this.listQuery.searchCourseId = ID;
                this.getCourseInfo(ID);
            }
            this.getList();
        },
        methods: {
            getList() {
                if (typeof this.listQuery.searchStatTimeStart == 'object') {
                    this.listQuery.searchStatTimeStart = parseTime(this.listQuery.searchStatTimeStart, '{y}-{m}-{d} 00:00:00');
                }
                if (typeof this.listQuery.searchStatTimeEnd == 'object') {
                    this.listQuery.searchStatTimeEnd = parseTime(this.listQuery.searchStatTimeEnd, '{y}-{m}-{d} 23:59:59');
                }
                if (!this.listQuery.searchStatTimeStart) {
                    this.$message({
                        title: '失败',
                        message: '原因:统计开始时间不能为空',
                        type: 'error',
                        duration: 3000
                    });
                    return false;
                }
                if (!this.listQuery.searchStatTimeEnd) {
                    this.$message({
                        title: '失败',
                        message: '原因:统计结束时间不能为空',
                        type: 'error',
                        duration: 3000
                    });
                    return false;
                }
                this.listLoading = true;
                getCourseDetailList(this.listQuery).then(response => {
                    this.list = response.data.data;
                    this.total = response.data.totalCount;
                    this.listLoading = false;
                }).catch(err => {
                    console.log(err)
                    this.listLoading = false;
                });
            },
            getCourseInfo(courseID) {
                getCourseDetail(courseID).then(response => {
                    this.courseName = response.data.name;
                }).catch(err => {
                    console.log(err)
                });
            },
            handleFilter() {
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.getList();
            },
            handleDownload() {
                if (!this.listQuery.searchStatTimeStart) {
                    this.$message({
                        title: '失败',
                        message: '原因:统计开始时间不能为空',
                        type: 'error',
                        duration: 3000
                    });
                    return false;
                }
                if (!this.listQuery.searchStatTimeEnd) {
                    this.$message({
                        title: '失败',
                        message: '原因:统计结束时间不能为空',
                        type: 'error',
                        duration: 3000
                    });
                    return false;
                }
                const copyQuery = JSON.parse(JSON.stringify(this.listQuery));
                copyQuery.page = 1;
                copyQuery.pageSize = 1000;
                if (typeof this.listQuery.searchStatTimeStart == 'object') {
                    copyQuery.searchStatTimeStart = parseTime(this.listQuery.searchStatTimeStart, '{y}-{m}-{d} 00:00:00');
                }
                if (typeof this.listQuery.searchStatTimeEnd == 'object') {
                    copyQuery.searchStatTimeEnd = parseTime(this.listQuery.searchStatTimeEnd, '{y}-{m}-{d} 23:59:59');
                }

                const fileName = '课程_' + this.courseName + '_统计';
                getCourseDetailList(copyQuery).then(response => {
                    const dataList = response.data.data;
                    require.ensure([], () => {
                        const { export_json_to_excel } = require('@/vendor/Export2Excel');
                        dataList.forEach(item => {
                            item.totalAmount = priceFormat(item.totalAmount);
                            item.dealAmount = priceFormat(item.dealAmount);
                            item.statDate = parseDate(item.statDate, 'day');
                        });
                        const tHeader = ['日期', '百度PV', '百度UV', '登陆用户的访问次数', '下单数', '下单金额(元)', '成交订单数', '成交金额(元)'];
                        const filterVal = ['statDate', 'pvCount', 'uvCount', 'accessCount', 'totalCount', 'totalAmount', 'dealCount', 'dealAmount'];
                        const data = this.formatJson(filterVal, dataList);
                        export_json_to_excel(tHeader, data, fileName);
                    })
                }).catch(err => {
                    console.log(err)
                });
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]))
            }
        }
    };
</script>